/**
 * Created by kenz on 2018/4/13.
 */

import { combineReducers } from 'redux'

import {
  SELECT_SUBREDDIT,
  INVALIDATE_SUBREDDIT,
  REQUEST_POSTS,
  RECEIVE_POSTS
} from '../constants'

const selectedsubreddit = (state = 'reactjs', action) => {
  switch (action.type) {
    case SELECT_SUBREDDIT:
      return action.subreddit

    default:
      return state
  }
}


const posts = (
  state = {
    isFetching: false, //显示进度条
    didInvalidate: false, //标记数据是否过期
    items: [] //列表数据
  },
  action
) => {
  switch (action.type) {
    case INVALIDATE_SUBREDDIT:
      return Object.assign({}, state, {didInvalidate: true})

    case REQUEST_POSTS:
      return Object.assign({}, state, {isFetching: true, didInvalidate: false})

    case RECEIVE_POSTS:
      return Object.assign({}, state, {
        isFetching: false,
        didInvalidate: false,
        items: action.posts,
        lastUpdated: action.receivedAt
      })
    default:
      return state
  }
}


const postsBySubreddit = (state = {}, action) => {
  switch (action.type) {
    case INVALIDATE_SUBREDDIT:
    case RECEIVE_POSTS:
    case REQUEST_POSTS:
      return Object.assign({}, state, {
        [action.subreddit]: posts(state[action.subreddit], action)
      })
    default:
      return state
  }
}


const rootReducers = combineReducers({
  postsBySubreddit,
  selectedsubreddit
})


export default rootReducers
